#ifndef __LOG_HPP__
#define __LOG_HPP__

#include<iostream>
#include<time.h>
#include<unistd.h>
#include<string>
#include<stdarg.h>
#include<pthread.h>

using namespace std;

//用于日志功能中对显示器加锁保护
pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;

//日志功能
//日志等级
enum LogLevel
{
    DEBUG=0,
    INFO,
    WARNING,
    ERROR,
    FATAL
};

//将日志等级转化为字符串
string LevelToString(int level)
{
    switch (level)
    {
    case DEBUG:
        return "Debug";
    case INFO:
        return "Info";
    case WARNING:
        return "Warning";
    case ERROR:
        return "Error";
    case FATAL:
        return "Fatal";
    default:
        return "Unknown";
    }
}

//获取特定的时间格式
string GetTimeString()
{
    time_t curr_time = time(nullptr);
    struct tm *format_time = localtime(&curr_time);
    if (format_time == nullptr)
        return "None";
    char time_buffer[1024];
    snprintf(time_buffer, sizeof(time_buffer), "%d-%d-%d %d:%d:%d",
             format_time->tm_year + 1900,
             format_time->tm_mon + 1,
             format_time->tm_mday,
             format_time->tm_hour,
             format_time->tm_min,
             format_time->tm_sec);
    return time_buffer;
}

void LogMsg(string filename,int line,int level,const char* format,...)
{
    std::string levelstr = LevelToString(level);
    std::string timestr = GetTimeString();
    pid_t selfid = getpid();
    char buffer[1024];
    va_list arg;
    va_start(arg, format);
    vsnprintf(buffer, sizeof(buffer), format, arg);
    va_end(arg);

    std::string message = "[" + timestr + "]" + "[" + levelstr + "]" +
                          "[" + std::to_string(selfid) + "]" +
                          "[" + filename + "]" + "[" + std::to_string(line) + "] " + buffer;
    pthread_mutex_lock(&log_lock);
    cout << message;
    pthread_mutex_unlock(&log_lock);
}

//宏定义
#define Log(level, format, ...)                                 \       
do                                                              \
{                                                               \
    LogMsg(__FILE__, __LINE__, level, format, ##__VA_ARGS__);   \
}                                                               \
while(0)

#endif